/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package za.co.sbi.sbiexam.service;

import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;

public class Service extends HttpServlet {

	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		ServiceController service = null;

		System.out.println("Starting...");

		try {

			System.out.println("Creating ServiceConroller");
			service = new ServiceController(request, response);
			String path = service.getPath();

			System.out.println("Path is: " + path);

			if (path.equals("/authenticate")) {

				System.out.println("Authentiate Called");

				boolean authenticated = authenticate(service);
				Session session = service.getSession();

				System.out.println("User is authenticated:" + authenticated);

				if (authenticated) {
					User user = session.getUser();
					session.update(user);

					session.addResponseField("response", "ok");
					session.addResponseField("authenticated", "true");
					session.addResponseField("fullname", user.getFirstname() + " " + user.getLastname());
					session.addResponseField("accessLevelId", new Long (user.getAccessLevelId()).toString());
					session.addResponseField("examcode", session.getSubmittedExamkey());

					System.out.println("Sending Response");
					service.sendResponse(session);

				} else {
				
					session.addResponseField("response", "ok");
					session.addResponseField("authenticated", "false");
					session.addResponseField("examkey", session.getSubmittedExamkey());

					System.out.println("Sending Response");
					service.sendResponse(session);
					
				}

			}

		} catch (Exception ex) {
			if (service != null) {
				service.handleError(ex);
			} else {
				throw new ServletException (ex);
			}
		}
	}

	public boolean authenticate(ServiceController service) throws ClassNotFoundException, SQLException {

		String method = service.getRequest().getParameter("method");

		if (method.equals(User.EXAMKEY)) {
			String examkey = service.getRequest().getParameter("examkey");
			return service.getSession().authenticate(examkey);
		}

		if (method.equals(User.USERPASS)) {
			throw new NotImplementedException();
		}

		throw new IllegalArgumentException("Only EXAMKEY and USERPASS Authentication methods are accepted");
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
}
